{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Steam and Leaf Plot\n",
    "-------------------\n",
    "This example shows how to make a steam and leaf plot.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import altair as alt\n",
    "alt.data_transformers.enable('json')\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "np.random.seed(42)\n",
    "\n",
    "# Generating random data\n",
    "original_data = pd.DataFrame({'samples': np.array(np.random.normal(50, 15, 100), dtype=np.int)})\n",
    "\n",
    "# Splitting steam and leaf\n",
    "original_data['stem'] = original_data['samples'].apply(lambda x: str(x)[:-1])\n",
    "original_data['leaf'] = original_data['samples'].apply(lambda x: str(x)[-1])\n",
    "\n",
    "original_data.sort_values(by=['stem', 'leaf'], inplace=True)\n",
    "original_data.reset_index(inplace=True, drop=True)\n",
    "\n",
    "# Determining leaf position\n",
    "get_position = lambda x: 1 + pd.Series(range(len(x)))\n",
    "\n",
    "original_data['position'] = original_data.groupby('stem')\\\n",
    "                                         .apply(get_position)\\\n",
    "                                         .reset_index(drop=True)\n",
    "\n",
    "# Creating stem and leaf plot\n",
    "alt.Chart(original_data).mark_text(\n",
    "    align='left',\n",
    "    baseline='middle',\n",
    "    dx=-5\n",
    ").encode(\n",
    "    alt.X('position:Q',\n",
    "        axis=alt.Axis(title='', ticks=False, labels=False, grid=False)\n",
    "    ),\n",
    "    alt.Y('stem:N', axis=alt.Axis(title='', tickSize=0)),\n",
    "    text='leaf:N'\n",
    ").configure_axis(\n",
    "    labelFontSize=20\n",
    ").configure_text(\n",
    "    fontSize=20\n",
    ")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "env": {},
   "interrupt_mode": "signal",
   "language": "python",
   "metadata": {},
   "name": "python3"
  },
  "language": "python"
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
